package com.quectel.core.module.partyeducationtraining.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quectel.constant.core.partyeducationtraining.TrainingPersonConstants;
import com.quectel.constant.global.SqlConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partyeducationtraining.dao.TrainingExperienceDao;
import com.quectel.core.module.partyeducationtraining.dto.TrainingDto;
import com.quectel.core.module.partyeducationtraining.dto.TrainingExperienceDto;
import com.quectel.core.module.partyeducationtraining.dto.TrainingPersonDto;
import com.quectel.core.module.partyeducationtraining.entity.TrainingExperienceEntity;
import com.quectel.core.module.partyeducationtraining.service.TrainingExperienceService;
import com.quectel.core.module.partyeducationtraining.service.TrainingPersonService;
import com.quectel.core.module.partyeducationtraining.service.TrainingService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 *
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2023/06/15 18:56
 */
@DubboService
public class TrainingExperienceServiceImpl implements TrainingExperienceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TrainingExperienceServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_EDUCATION_TRAINING_EXPERIENCE_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_EDUCATION_TRAINING_EXPERIENCE_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<TrainingExperienceDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_EDUCATION_TRAINING_EXPERIENCE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private TrainingExperienceDao trainingExperienceDao;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private TrainingService trainingService;
    @Autowired
    private PartyPersonService partyPersonService;
    @Autowired
    private TrainingPersonService trainingPersonService;


    @Override
    @Transactional
    public void saveAndUpdate(TrainingExperienceDto trainingExperienceDto) {
        save(trainingExperienceDto);

        TrainingPersonDto dbTrainingPersonDto = trainingPersonService.selectOne(trainingExperienceDto.getTrainingId(), trainingExperienceDto.getPartyPersonId());
        if (Objects.nonNull(dbTrainingPersonDto)) {
            TrainingPersonDto updateObj = new TrainingPersonDto();
            updateObj.setId(dbTrainingPersonDto.getId());
            updateObj.setExperienceSubmitted(TrainingPersonConstants.SubmittedEnum.SUBMITTED.getStatus());
            trainingPersonService.updateById(updateObj);
        }
    }

    @Override
    public TrainingExperienceDto selectOne(Long personId, Long trainingId) {
        TrainingExperienceEntity trainingExperienceEntity = trainingExperienceDao.selectOne(new LambdaQueryWrapper<TrainingExperienceEntity>()
                .eq(TrainingExperienceEntity::getPartyPersonId, personId)
                .eq(TrainingExperienceEntity::getTrainingId, trainingId)
                .last(SqlConstants.MYSQL_LIMIT_ONE));
        TrainingExperienceDto trainingExperienceDto = CopyUtils.copyObj(trainingExperienceEntity, TrainingExperienceDto.class);
        paddingField(trainingExperienceDto);
        return trainingExperienceDto;
    }

    @Override
    public TrainingExperienceDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_EDUCATION_TRAINING_EXPERIENCE_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public TrainingExperienceDto selectById(Long id){
            TrainingExperienceEntity entity = trainingExperienceDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, TrainingExperienceDto.class));
    }

    @Override
    public List<TrainingExperienceDto> queryList(Map<String,Object> params){
        List<TrainingExperienceEntity> list = trainingExperienceDao.queryList(params);
        List<TrainingExperienceDto> result =  CopyUtils.copyList(list, TrainingExperienceDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<TrainingExperienceDto> queryListWithoutPadding(Map<String,Object> params){
        List<TrainingExperienceEntity> list = trainingExperienceDao.queryList(params);
        return CopyUtils.copyList(list, TrainingExperienceDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private TrainingExperienceDto paddingField(TrainingExperienceDto dto){
        if (dto != null){
            PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectCacheById(dto.getPartyId());
            dto.setParty(partyOrganizationDto);

            TrainingDto trainingDto = trainingService.selectById(dto.getTrainingId());
            dto.setTraining(trainingDto);

            PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(dto.getPartyPersonId());
            dto.setPartyPerson(partyPersonDto);
        }
        return dto;
    }

    /**
     * 关联更新评价数
     *
     * @param trainingId 课程id
     * @param c          计数
     */
    private void changeTrainingExperienceCount(Long trainingId, int c) {
        TrainingDto dbTrainingDto = trainingService.selectById(trainingId);
        TrainingDto newlyDto = new TrainingDto();
        newlyDto.setId(dbTrainingDto.getId());
        newlyDto.setTrainingCommentCount(dbTrainingDto.getTrainingExperienceCount() == null
                ? c : dbTrainingDto.getTrainingExperienceCount() + c);
        trainingService.updateById(newlyDto);
    }

    @Override
    public int queryTotal(Map<String, Object> params){
        return trainingExperienceDao.queryTotal(params);
    }

    @Override
    public Long save(TrainingExperienceDto dto){
        TrainingExperienceEntity entity = CopyUtils.copyObj(dto, TrainingExperienceEntity.class);
        entity.setId(Snowflake.nextId());
        trainingExperienceDao.insert(entity);
        changeTrainingExperienceCount(dto.getTrainingId(), 1);
        return entity.getId();
    }

    @Override
    public void updateById(TrainingExperienceDto dto){
        TrainingExperienceEntity entity = CopyUtils.copyObj(dto, TrainingExperienceEntity.class);

        trainingExperienceDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void updateAllColumnById(TrainingExperienceDto dto) {
       TrainingExperienceEntity entity = CopyUtils.copyObj(dto, TrainingExperienceEntity.class);

       MyBatisPlusUtils.updateAllColumnById(entity, trainingExperienceDao);

       CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id){

        CLEAR_CACHE_FUNC.accept(selectById(id));

        trainingExperienceDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids){
        for (Long id : ids) {
            TrainingExperienceDto trainingExperienceDto = selectCacheById(id);
            if (trainingExperienceDto != null) {
                changeTrainingExperienceCount(trainingExperienceDto.getTrainingId(), -1);
            }
            deleteById(id);
        }
    }
}
